//
//  ViewController.m
//  瀑布流布局
//
//  Created by 红蜀黍 on 15/5/6.
//  Copyright (c) 2015年 红蜀黍. All rights reserved.
//

#import "ViewController.h"
#import "Shops.h"
#import "WaterFlowLayout.h"
#import "WaterImageCell.h"
#import "WaterfallFooterView.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet WaterFlowLayout *layout;
@property (nonatomic, strong) NSMutableArray *shops;

/************ 当前数据的索引 ************/
@property (nonatomic, assign) NSInteger index;

// 页脚视图
@property (nonatomic, weak) WaterfallFooterView *footerView;
// 正在加载标记
@property (nonatomic, assign, getter=isLoading) BOOL loading;
@end

@implementation ViewController

- (void)loadData
{
    [self.shops addObjectsFromArray:[Shops shopWithIndex:self.index]];
    
    self.index++;
    
    // 设置布局属性
    self.layout.columnCount = 3;
    self.layout.dataList = self.shops;
    
    
    // 刷新数据
    [self.collectionView reloadData];
}

#pragma mark - 数据源
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.shops.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WaterImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];

    
    cell.shop = self.shops[indexPath.item];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionFooter) {
        self.footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footView" forIndexPath:indexPath];
        return self.footerView;
    }
    return nil;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.footerView == nil || self.isLoading) {
        return;
    }
    
    if ((scrollView.contentOffset.y + scrollView.bounds.size.height) > self.footerView.frame.origin.y) {
        NSLog(@"开始刷新");
        
        self.loading = YES;
        [self.footerView.indicaator startAnimating];
        
        // 模拟数据刷新
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 释放footView
            self.footerView = nil;
            
//            [self.collectionView reloadData];
            [self loadData];
            self.loading = NO;
        });
    }
}



- (NSMutableArray *)shops
{
    if (_shops == nil) {
        _shops = [NSMutableArray array];
    }
    return _shops;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 加载数据
    [self loadData];
    
}

@end
